<?php

namespace CommonBundle\EventListener;

use CommonBundle\Entity\User;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;


class ControllerListener
{
    /** @var ContainerInterface */
    private $container;
    /** @var TokenStorage */
    private $tokenStorage;
    /** @var object|\Symfony\Bridge\Monolog\Logger */
    private $logger;

    public function __construct(ContainerInterface $container, TokenStorage $tokenStorage)
    {
        $this->container = $container;
        $this->tokenStorage = $tokenStorage;
        $this->logger = $container->get('monolog.logger.access');
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        // get operation user
        if ($this->tokenStorage->getToken()) {
            /** @var User $operator */
            $operator = $this->tokenStorage->getToken()->getUser();
            if($operator instanceof User) $operator = $operator->getId();
        }
        else return;

        $controller = $event->getController();
        $request = $event->getRequest();

        $method = $request->getMethod();
        $uri = $request->getRequestUri();

        $content = $request->getContent();
        if(strlen($content) > 1024 /* 1K */) {
            $content = '...';
        }

        if(preg_match("/(PUT|POST)/i", $method)) {
            $this->logger->info(
                "User [#$operator] Requests $method $uri: $content"
            );
        }
    }
}